﻿using BotDetector.Core.NaiveBayesModule;
using BotDetector.Core.SVMModule;
using BotDetector.Core.TextPreprocessing;
using BotDetector.Core.Utilities;
using BotDetector.Core.WebModule;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

namespace BotDetector.Core
{
    public class Detector
    {
        private TextPreprocessor textPreprocessor;
        private List<DetectorBaseModule> baseModules = new List<DetectorBaseModule>();
        private List<DetectorAuxiliaryModule> auxiliaryModules = new List<DetectorAuxiliaryModule>();

        public Detector()
        {
            textPreprocessor = new TextPreprocessor();
            InitModules();
        }

        private void InitModules()
        {
            BayesTest bayesTest = new BayesTest();
            if (bayesTest.HasClassifier())
            {
                baseModules.Add(bayesTest);
            }

            SvmTest svmTest = new SvmTest();
            if(svmTest.HasClassifier())
            {
                baseModules.Add(svmTest);
            }

            auxiliaryModules.Add(new WebTest());
        }

        public double Classify(string text)
        {
            string processedText = textPreprocessor.Preprocess(text);
            double rez = 0;

            foreach (DetectorModule module in baseModules)
            {
                rez += module.TestForBot(processedText);
            }
            if(rez != 0)
            {
                rez /= baseModules.Count;
            }

            double min = Constants.MinProbabilityToStartWebSearch;
            double max = Constants.MaxProbabilityToStartWebSearch;
            if ((rez > min && rez < max) || baseModules.Count == 0)
            {
                double rezAux = 0;
                foreach(DetectorModule module in auxiliaryModules)
                {
                    rezAux += module.TestForBot(text);
                }
                if (rezAux != 0)
                {
                    rez = (rez + rezAux) / 2;
                }
            }
            
            return rez;
        }          
    }
}
